package com.elective.courseselect.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.elective.courseselect.dao.CharacterMatchDao;
import com.elective.courseselect.dao.CourseCharacterDao;
import com.elective.courseselect.dao.CourseDao;
import com.elective.courseselect.dao.StudentCharacterDao;
import com.elective.courseselect.entity.*;
import com.elective.courseselect.service.*;
import com.elective.courseselect.serviceUtils.CourseUtils;
import com.elective.courseselect.serviceUtils.UserUtils;
import com.elective.courseselect.utils.PageUtils;
import com.elective.courseselect.utils.Query;
import com.elective.courseselect.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Service("characterMatchService")
@Transactional(rollbackFor = Exception.class)
public class CharacterMatchServiceImpl extends ServiceImpl<CharacterMatchDao, CharacterMatchEntity> implements CharacterMatchService {


    @Autowired
    StudentCharacterService studentCharacterService;

    @Autowired
    StudentCharacterDao studentCharacterDao;

    @Autowired
    CourseCharacterService courseCharacterService;

    @Autowired
    CourseCharacterDao courseCharacterDao;

    @Autowired
    CourseService courseService;

    @Autowired
    CourseDao courseDao;


    @Autowired
    CharacterService characterService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CharacterMatchEntity> page = this.page(
                new Query<CharacterMatchEntity>().getPage(params),
                new QueryWrapper<CharacterMatchEntity>()
        );
        for (CharacterMatchEntity record : page.getRecords()) {
            record.setCourseCharacterName(characterService.getById(record.getCourseCharacterId()).getLabel());
            record.setCharacterLabelName(characterService.getById(record.getCharacterLabelId()).getLabel());
        }
        return new PageUtils(page);
    }

    @Override
    public List<CourseEntity> searchRecommendChooseClass(Integer userId) {
        //临时存储course_characterIdList
        Set<Integer> tempCourseIdsSet = new HashSet<>();


        // 查询学生性格表，拿到当前学生性格标签
        QueryWrapper<StudentCharacterEntity> studentCharacterQuery = new QueryWrapper<>();
        studentCharacterQuery.eq("student_id", userId);
        StudentCharacterEntity studentCharacterEntity = studentCharacterService.getOne(studentCharacterQuery);
        for (String characterId : studentCharacterEntity.getCharacterId().split(",")) {
            // 查询character_match 目的获取course_character表信息， 根据course_character 表信息，能拿到当课程id
            QueryWrapper<CharacterMatchEntity> characterMatchQuery = new QueryWrapper<>();
            characterMatchQuery.eq("character_label_id", characterId);
            List<CharacterMatchEntity> list = this.list(characterMatchQuery);


            for (CharacterMatchEntity characterMatchEntity : list) {
                tempCourseIdsSet.add(characterMatchEntity.getCourseCharacterId());
            }
        }


        List<CourseEntity> resList = new ArrayList<>();
        HashMap<Integer, Set<String>> map = new HashMap<>();
        if (!tempCourseIdsSet.isEmpty()) {
            QueryWrapper<CourseCharacterEntity> courseCharacterEntityQueryWrapper = new QueryWrapper<>();
            Set<CourseCharacterEntity> courseCharacterEntityList = new HashSet<>();
            for (Integer courseCharacterId : tempCourseIdsSet) {
                courseCharacterEntityQueryWrapper.eq("character_id", courseCharacterId);
                courseCharacterEntityList.addAll(courseCharacterDao.selectList(courseCharacterEntityQueryWrapper));
            }
            for (CourseCharacterEntity courseCharacterEntity : courseCharacterEntityList) {
                //课程基本信息
                CourseEntity courseEntity = courseService.getById(courseCharacterEntity.getCourseId());
                //过滤老师被弃用的课程
                Boolean abandon = UserUtils.isAbandon(courseEntity.getTeacherId());
                if (abandon) {
                    continue;
                }
                //过滤不正常的课程
                Boolean courseIsAbandon = CourseUtils.courseIsAbandon(courseCharacterEntity.getCourseId());
                if (courseIsAbandon) {
                    continue;
                }


                //判断结果集是否存储过，重新设置标签
                Boolean flag = false;
                for (int i = 0; i < resList.size(); i++) {
                    CourseEntity entity = resList.get(i);
                    if (entity.getId() == courseEntity.getId()) {
                        Set<String> labelNameList = entity.getLabelNameList();
                        CharacterEntity characterEntity = characterService.getById(courseCharacterEntity.getCharacterId());
                        String label = characterEntity.getLabel();
                        labelNameList.add(label);
                        entity.setLabelNameList(labelNameList);
                        entity.setScheduleByJson((JSONObject) JSONObject.parse(entity.getSchedule()));
                        resList.remove(i);
                        resList.add(entity);
                        flag = true;
                        break;
                    }
                }
                if (flag == true) {
                    continue;
                }else{
                    HashSet<String> tempSet = new HashSet<>();
                    CharacterEntity characterEntity = characterService.getById(courseCharacterEntity.getCharacterId());
                    String label = characterEntity.getLabel();
                    tempSet.add(label);
                    courseEntity.setLabelNameList(tempSet);
                    courseEntity.setScheduleByJson((JSONObject) JSONObject.parse(courseEntity.getSchedule()));
                    resList.add(courseEntity);
                }
            }
        }
        return resList;
    }

    @Override
    public R searchCharacterMatchReleation(Integer searchId, Integer type) {
        QueryWrapper<CharacterMatchEntity> characterMatchEntityQueryWrapper = new QueryWrapper<>();
        switch (type) {
            case 0:
                characterMatchEntityQueryWrapper.eq("character_label_id", searchId);
                break;
            case 1:
                characterMatchEntityQueryWrapper.eq("course_character_id", searchId);
                break;
            default:
                break;
        }
        HashMap<Integer,  String> resMap = new HashMap<>();
        List<CharacterMatchEntity> list = this.list(characterMatchEntityQueryWrapper);
        for (CharacterMatchEntity characterMatchEntity : list) {
            characterMatchEntity.setCourseCharacterName(characterService.getById(characterMatchEntity.getCourseCharacterId()).getLabel());
            characterMatchEntity.setCharacterLabelName(characterService.getById(characterMatchEntity.getCharacterLabelId()).getLabel());
            if (type == 0) {
                resMap.put(characterMatchEntity.getCourseCharacterId(), characterMatchEntity.getCourseCharacterName());
            }
            if (type == 1) {
                resMap.put(characterMatchEntity.getCharacterLabelId(), characterMatchEntity.getCharacterLabelName());
            }
        }
        return R.ok().put("data", resMap);
    }

    @Override
    public R updateCharacterMatchReleation(Integer searchId, Integer type, Integer[] content) {
        QueryWrapper<CharacterMatchEntity> characterMatchEntityQueryWrapper = new QueryWrapper<>();
        switch (type) {
            case 0:
                characterMatchEntityQueryWrapper.eq("character_label_id", searchId);
                break;
            case 1:
                characterMatchEntityQueryWrapper.eq("course_character_id", searchId);
                break;
            default:
                break;
        }
        List<CharacterMatchEntity> list = this.list(characterMatchEntityQueryWrapper);
        for (CharacterMatchEntity characterMatchEntity : list) {
            this.removeById(characterMatchEntity.getId());
        }
        if (content != null && content.length > 0) {
            for (Integer characterId : content) {
                CharacterMatchEntity characterMatchEntity = new CharacterMatchEntity();
                if (type == 0) {
                    characterMatchEntity.setCharacterLabelId(searchId);
                    characterMatchEntity.setCourseCharacterId(characterId);
                }
                if (type == 1) {
                    characterMatchEntity.setCourseCharacterId(searchId);
                    characterMatchEntity.setCharacterLabelId(characterId);
                }
                this.save(characterMatchEntity);
            }
        }
        return R.ok();
    }

}